<template>
  <div class="xtx-pagination">
    <a @click="changePage(myCurrPage-1)" v-if="myCurrPage>1" href="javascript:;" >上一页</a>
    <a v-else href="javascript:;" class="disabled">上一页</a>
    <span v-if="pager.start>1">...</span>
    <a @click="changePage(i)" v-for="i in pager.btnArr" :key="i" href="javascript:;" :class="{active:myCurrPage===i}">{{ i }}</a>

    <span v-if="pager.end<pager.pageCount">...</span>
    <a @click="changePage(myCurrPage+1)" v-if="myCurrPage<pager.pageCount" href="javascript:;">下一页</a>
    <a v-else href="javascript:;" class="disabled">下一页</a>
  </div>
</template>
<script setup>
const props = defineProps({
  total: {
    type: Number,
    default: 100
  },
  pageSize: {
    type: Number,
    default: 10
  },
  currPage: {
    type: Number

  }
})
// 需要的数据
// 1.约定按钮个数
const count = 5
// 2.当前显示的页码
const myCurrPage = ref(1)
// 3.总页数 = 总条数 / 每页展示条数 向上取整
const myTotal = ref(100)
const myPageSize = ref(10)
// 其他数据通过上面计算得出
const pager = computed(() => {
  const pageCount = Math.ceil(myTotal.value / myPageSize.value)
  // 依赖按钮个数,和当前页得到起始页和结束页
  // 理想状态下
  const offset = Math.floor(count / 2)
  let start = myCurrPage.value - offset
  let end = start + count - 1
  // 特殊情况,如果起始页小于1
  if (start < 1) { // 起始判断
    start = 1
    end = (start + count - 1) > pageCount ? pageCount : (start + count - 1)
  }
  if (end > pageCount) { // 结束判断
    end = pageCount
    start = (end - count + 1) < 1 ? 1 : (end - count + 1)
  }
  const btnArr = []
  for (let i = start; i <= end; i++) {
    btnArr.push(i)
  }
  return { pageCount, btnArr, start, end }
})
// 监听props数据变化,更新模板数据
watch(props, () => {
  myTotal.value = props.total
  myPageSize.value = props.pageSize
  myCurrPage.value = props.currPage
}, {
  immediate: true
})
const emit = defineEmits(['change'])
const changePage = (page) => {
  emit('change', page)
}
</script>

<script>
export default {
  name: 'XtxPagination'
}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>
